package com.zynote.nfhoujie.dao.impl;

import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import com.zynote.commons.base.BaseDAOHibernate;
import com.zynote.nfhoujie.commons.utils.Constants;
import com.zynote.nfhoujie.dao.IUserDAO;
import com.zynote.nfhoujie.model.User;


/**
 * 
 * @className:UserDAOImpl.java
 * @classDescription:用户数据访问层实现类
 * @author: AIDAN SU
 * @createTime: 2012-10-7
 *
 */

@Repository("userDAO")
public class UserDAOImpl extends BaseDAOHibernate implements IUserDAO {

	@Override
	protected Class<User> getModelClass() {
		return User.class;
	}
	
	@Override
	public User findUserById(Long id) {
		return  (User)doFindObjectById(id);
	}
	
	@Override
	public Long createUser(User user) {
		return (Long)doCreateObject(user);
		
	}
	
	@Override
	public void updateUser(User user) {
		doUpdateObject(user);
	}
	
	@Override
	public void deleteUser(User user) {
		doDeleteObject(user);
		
	}
	
	@Override
	public void deleteUserById(Long id) {
		doDeleteObject( findUserById( id ) ) ;
	}

	@SuppressWarnings("unchecked")
	@Override
	public User findUserByUsername(String username) {
		User user = null ;
		List<User> users = null ;
		
		Session session = super.getSession();
		
		try{
			users = doQueryHQL( "   from User u where u.username=?", session) 
							.setString(0, username)
							.list();
			if( users != null && users.size() > 0 ){
				//总是返回用户列表的第一个用户
				user= users.get(0);
			}
		}catch( Exception e){
			
		}finally{
			releaseSession(session);
		}
		
		return user;
	}

	@SuppressWarnings("unchecked")
	@Override
	public User findUserByUsernameAndPassword(String username, String password,int userType) {
		
		User user = null ;
		List<User> users = null ;
		
		Session session = super.getSession();
		
		String hql = "  from User u where u.username=? and u.password=? " ;
	
		//如果不是所有用户，需要加上此条件
		if( Constants.USER_TYPE_ALL != userType ){
			hql += " and u.userType=? ";
		}
		
		try{
			
			Query query = doQueryHQL( hql , session) 
							.setString(0, username)
							.setString(1, password) ;
			
			if( Constants.USER_TYPE_ALL != userType ){
				query.setInteger(2, userType);
			}
			
			users = query.list();
			
			if( users != null && users.size() > 0 ){
				//总是返回用户列表的第一个用户
				user= users.get(0);
			}
		}catch( Exception e){
			
		}finally{
			releaseSession(session);
		}
		
		return user;
	}

	@Override
	public int countUsers(String hqlCondition) {
		return doCountSingleObject(hqlCondition);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> listUsers(int startPosition, int pageSize, String hqlCondition, Map<String, String> orderProperties) {
		return doListSingleObject(startPosition, pageSize, hqlCondition, orderProperties);
	}

}
